package com.itstyle.quartz.service.impl;

import com.itstyle.quartz.dynamicquery.DynamicQuery;
import com.itstyle.quartz.entity.DetailsBean;
import com.itstyle.quartz.entity.PageBean;
import com.itstyle.quartz.entity.Result;
import com.itstyle.quartz.service.IDetailsBeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service("DetailsBeanImpl")
public class DetailsBeanImpl implements IDetailsBeanService {


    @Autowired
    private DynamicQuery dynamicQuery;

    @Override
    @Transactional(readOnly = true)
    public Result listDetailsBean(DetailsBean detailsBean, Integer pageNo, Integer pageSize) {
        String countSql = "SELECT COUNT(*) FROM detailsbean";
        Long totalCount = dynamicQuery.nativeQueryCount(countSql);
        PageBean<DetailsBean> data = new PageBean<>();
        if (totalCount > 0) {
            StringBuffer nativeSql = new StringBuffer();
            nativeSql.append("SELECT * FROM detailsbean ");
            Object[] params = new Object[]{};
            if (!StringUtils.isEmpty(detailsBean.getUserId())) {
                nativeSql.append("WHERE userId = ?");
                params = new Object[]{detailsBean.getUserId()};
            }
            Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
            List<DetailsBean> list = dynamicQuery.nativeQueryPagingList(DetailsBean.class, pageable, nativeSql.toString(), params);
            data = new PageBean<>(list, totalCount);
        }
        return Result.ok(data);
    }

    @Override
    @Transactional
    public Result save(DetailsBean detailsBean) {
        dynamicQuery.save(detailsBean);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result delete(DetailsBean detailsBean) {
        dynamicQuery.delete(DetailsBean.class, detailsBean.getUserId());
        return Result.ok();
    }

    @Override
    @Transactional
    public Result update(DetailsBean detailsBean) {
        dynamicQuery.update(detailsBean);
        return Result.ok();
    }
}
